package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var count int = 1
var rw *sync.RWMutex = new(sync.RWMutex) //读写互斥锁
/*
读读不互斥
读写互斥
写写互斥
*/
func main() {
	ch := make(chan int, 6)
	for i := 0; i < 3; i++ {
		go ReadCount(i, ch)
	}
	//time.Sleep(100*time.Millisecond)
	for i := 0; i < 3; i++ {
		go WriteCount(i, ch)
	}

	for i := 0; i < 6; i++ {
		<-ch
	}
}

func ReadCount(n int, ch chan int) {
	rw.RLock() //加读锁
	fmt.Printf("goroutine %d 进入读操作\n", n)
	v := count
	time.Sleep(100 * time.Millisecond)
	fmt.Printf("gouroutine %d 结束读操作，值为：%d\n", n, v)
	rw.RUnlock()
	ch <- v
}

func WriteCount(n int, ch chan int) {
	rw.Lock() //加写锁
	fmt.Printf("goroutine %d 进入写操作\n", n)
	v := rand.Intn(10) //写入随机值
	count = v
	time.Sleep(100 * time.Millisecond)
	fmt.Printf("gouroutine %d 结束写操作，新值为：%d\n", n, v)
	rw.Unlock()
	ch <- v
}
